/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Whitemice.ZOGI;
using Whitemice.ZOGI.GtkWidgets;
using Gtk;

namespace Whitemice.ZOGI.GtkFolios
{
	[System.ComponentModel.Category("widget")]
	[System.ComponentModel.ToolboxItem(true)]
	public class ContactTab : Gtk.ScrolledWindow, IEntityForm, IZOGIWidget
	{
		Whitemice.ZOGI.GtkWidgets.ContactNodeView contacts;
		
		public EntityEventHandler                     OnContactEdit;
		public EntityEventHandler                     OnContactRemove;
		public EntityEventHandler                     OnContactUnassign;
		public EventHandler                           OnDataReceived;
		protected MultiResultCallback                 fillCallback;
    protected int                                currentObjectId; 
	
		public ContactTab()
		{
			this.HscrollbarPolicy = PolicyType.Automatic;
			this.VscrollbarPolicy = PolicyType.Always;			
			contacts = new ContactNodeView(null, true);
			contacts.OnContactEdit = new EntityEventHandler(ContactEdit);
			contacts.OnContactRemove = new EntityEventHandler(ContactRemove);
			contacts.OnContactUnassign = new EntityEventHandler(ContactUnassign);
			fillCallback = new MultiResultCallback(this.ReceiveDataCallback);
			this.Child = contacts;		
		}
		
		public bool PopupEnabled
    { 
      get { return contacts.PopupEnabled; }
      set { contacts.PopupEnabled =  value; }
    }
		
		public void Clear()
		{
			contacts.Clear();
		} // end Clear
		
		public void Fill(Entity entity)
		{
			IContactContainer	container;
      
			// we keep the objectId of the last object poured in the form
      // so that we can verify the identify of subsequently received
      // data from the async. server call
      currentObjectId = entity.ObjectId;
			if (entity is Whitemice.ZOGI.IContactContainer)
				container = (entity as Whitemice.ZOGI.IContactContainer);
				else throw new Exception("Inappopriate entity type provided to form");
      /*
      FetchCommand      command;
      var contactIds = container.ContactIds;
		  this.ZLOG("Issuing request for {0} contacts", contactIds.Count());
      command = new FetchCommand(contactIds, 65535, currentObjectId);
      command.Callback = fillCallback;
      Server.Connection.RunCommand(command);
      */
      container.GetContacts(fillCallback, currentObjectId);
		} // end Fill
		
		public void ReceiveRPCCall(RPCEventArgs args)
		{
      this.ZLOG("ReceiveRPCCall");
      if (args.IsError)
      {
        // TODO: Raise error message box for ContactTab RPC exception
        this.ZLOG(args.Exception.Message);
        this.ZLOG(args.Exception.StackTrace);
      } else
        {
          // We discard received data if the context is not the objectId of the
          // currently displayed contact.  This is because scrolling around
          // in a CRUD form the data here may lag that displayed in the detail
          // section and we do not want to display incorrect information.  The
          // correct data should be received eventually. :)
          if (Convert.ToInt32(args.Context) == currentObjectId)
          {
            this.ZLOG("Filling contact tab with {0} contacts", args.Payload.Count());
            contacts.Fill(args.Payload);
          } else this.ZLOG("Discarding {0} received contacts due to objectId#{1} mismatch", 
                           args.Payload.Count(),
                           currentObjectId);
        }
      if (OnDataReceived != null)
        OnDataReceived(this, null);
		} // end FillCallback
		
		protected virtual void ContactEdit(
		  Entity _entity,
			object _context, 
			Exception _ex)
		{ OnContactEdit(_entity, _context, _ex); }

		protected virtual void ContactRemove(
		  Entity _entity,
			object _context, 
			Exception _ex)
		{ OnContactRemove(_entity, _context, _ex); }

		protected virtual void ContactUnassign(
		  Entity _entity,
			object _context, 
			Exception _ex)
		{ OnContactUnassign(_entity, _context, _ex); }		
	}
}